<script  lang="ts">
import {User, Lock} from '@element-plus/icons-vue'
import { defineComponent, ref } from "vue";
import axios from "axios";
import 'element-plus/dist/index.css' // <-- 必须引入样式！
import router from "../../router";
import {ElMessage} from "element-plus";
export default defineComponent({
  name: "Login",
  computed: {
  },
  setup() {
    const username = ref("");
    const password = ref("");
    const errorMessage = ref("");
    const role = ref("CUSTOMER")
//定义表单校验规则
    const handleLogin = async () => {
      if(!username.value )
      {
        ElMessage.error('请输入用户名!');
        return;
      }
      if(!password.value )
      {
        ElMessage.error('请输入密码!');
        return;
      }
      if( !role.value)
      {
        ElMessage.error('请选择角色!');
        return;
      }

      try {
        const response = await axios.post("/api/login/", {
          username: username.value,
          password: password.value,
          role: role.value
        });
        if (response.data.success) {
          ElMessage.info("登录成功");
          sessionStorage.setItem('isLoggedIn', 'true');
          sessionStorage.setItem('userRole', role.value);

          sessionStorage.setItem('username', username.value);
          sessionStorage.setItem('password', password.value);
          sessionStorage.setItem('userId',response.data.userId);
          switch (role.value){
            case 'SELLER':
              await router.push({ path: "/seller" });
              break;
            case 'CUSTOMER':
              const info =await axios.get('/api/customer/profile',{params: {username:username.value}});

              sessionStorage.setItem('email',info.data.email);
              sessionStorage.setItem('address',info.data.address);
              await router.push({ path: "/customer" });
              break;
            case 'ADMIN':
              await router.push({ path: "/admin" });
              break;
          }

        } else {
          errorMessage.value = response.data.message || "用户名或密码错误";
          ElMessage.error(errorMessage.value);
        }
      } catch (error) {
        //ElMessage.error(error.toString());
        ElMessage.error(  "请求失败，请稍后重试");
        console.error("登录请求失败", error);
      }
    };
    const navigateToRegister = () => {
      router.push({ path: "/register" });
    }
    return {
      username,
      password,
      errorMessage,
      role,
      handleLogin,
      navigateToRegister,
      User,
      Lock,
    };
  },
});



</script>

<template>
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">

      <!-- 登录表单 -->
      <el-form ref="form" size="large" autocomplete="off" >
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="password"></el-input>
        </el-form-item>
        <el-form-item prop="role">
          <el-select v-model="role" placeholder="请选择角色">
            <el-option label="消费者" value="CUSTOMER"  />
            <el-option label="商家" value="SELLER"/>
            <el-option label="管理员" value="ADMIN" />
          </el-select>
        </el-form-item>

        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>
        <!-- 登录按钮 -->
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="handleLogin()">登录</el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="navigateToRegister()">
            注册 →
          </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>

</template>

<style lang="scss" >

/* 样式 */
.login-page {
  height: 100vh;
  background-color: #fff;

  .bg {
    background: url('public/assets/emall_logo.png') no-repeat 60% center / 360px auto,
    url('public/assets/login_bg.jpg') no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }

  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;

    .title {
      margin: 0 auto;
    }

    .button {
      width: 100%;
    }

    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
body {
  margin: 0;
  background-color: #f5f5f5;
}

/* fade-slide */
.fade-slide-leave-active,
.fade-slide-enter-active {
  transition: all 0.3s;
}

.fade-slide-enter-from {
  transform: translateX(-30px);
  opacity: 0;
}

.fade-slide-leave-to {
  transform: translateX(30px);
  opacity: 0;
}
</style>